package com.szh.gulimall.ware.service.impl;

import com.szh.common.constant.WareConstant;
import com.szh.gulimall.ware.entity.PurchaseDetailEntity;
import com.szh.gulimall.ware.service.PurchaseDetailService;
import com.szh.gulimall.ware.service.WareSkuService;
import com.szh.gulimall.ware.vo.FinishPurchaseVo;
import com.szh.gulimall.ware.vo.MergePurchaseDetailVo;
import com.szh.gulimall.ware.vo.PurchaseItemVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.szh.common.utils.PageUtils;
import com.szh.common.utils.Query;
import com.szh.gulimall.ware.dao.PurchaseDao;
import com.szh.gulimall.ware.entity.PurchaseEntity;
import com.szh.gulimall.ware.service.PurchaseService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

@Service("purchaseService")
public class PurchaseServiceImpl extends ServiceImpl<PurchaseDao, PurchaseEntity> implements PurchaseService {

    @Autowired
    private PurchaseDetailService purchaseDetailService;

    @Autowired
    private WareSkuService wareSkuService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        QueryWrapper<PurchaseEntity> queryWrapper = new QueryWrapper<>();
        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)) {
            queryWrapper.and(obj -> obj.eq("assignee_id", key).or().like("assignee_name", key));
        }
        String status = (String) params.get("status");
        if (!StringUtils.isEmpty(status)) {
            queryWrapper.eq("status", status);
        }
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                queryWrapper
        );
        return new PageUtils(page);
    }

    /**
     * 查询所有未领取的采购单
     */
    @Override
    public PageUtils queryUnreceivePurchaseList(Map<String, Object> params) {
        QueryWrapper<PurchaseEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("status",
                WareConstant.PurchaseStatusEnum.CREATED.getCode(), WareConstant.PurchaseStatusEnum.ASSIGNED.getCode());
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                queryWrapper
        );
        return new PageUtils(page);
    }

    /**
     * 将多个采购需求合并为一个采购单
     */
    @Override
    @Transactional
    public void mergePurchaseDetail(MergePurchaseDetailVo purchaseDetailVo) {
        Long purchaseId = purchaseDetailVo.getPurchaseId();
        //如果采购单id为空，则新建一个采购单
        if (Objects.isNull(purchaseId)) {
            PurchaseEntity purchaseEntity = new PurchaseEntity();
            //状态为新建
            purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.CREATED.getCode());
            purchaseEntity.setCreateTime(new Date());
            purchaseEntity.setUpdateTime(new Date());
            this.save(purchaseEntity);
            purchaseId = purchaseEntity.getId();
        }
        //当采购需求的状态是新建或者已分配时，才可以合并成采购单，而后将这些采购需求的状态改为已分配
        List<Long> items = purchaseDetailVo.getItems();
        QueryWrapper<PurchaseDetailEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("id", items);
        List<PurchaseDetailEntity> purchaseDetailEntities = purchaseDetailService.list(queryWrapper);
        List<Integer> statusList = purchaseDetailEntities.stream().map(PurchaseDetailEntity::getStatus).collect(Collectors.toList());
        //当这些采购需求的状态不是枚举类中的2、3、4时，才可以进行合并
        if (!statusList.contains(WareConstant.PurchaseDetailStatusEnum.BUYING.getCode()) &&
            !statusList.contains(WareConstant.PurchaseDetailStatusEnum.FINISH.getCode()) &&
            !statusList.contains(WareConstant.PurchaseDetailStatusEnum.HASERROR.getCode())) {
            Long finalPurchaseId = purchaseId;
            List<PurchaseDetailEntity> purchaseDetailEntityList = items.stream().map(item -> {
                PurchaseDetailEntity detailEntity = new PurchaseDetailEntity();
                detailEntity.setId(item);
                detailEntity.setPurchaseId(finalPurchaseId);
                detailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.ASSIGNED.getCode());
                return detailEntity;
            }).collect(Collectors.toList());
            purchaseDetailService.updateBatchById(purchaseDetailEntityList);
            //最后将采购单的更新时间update_time更新一下
            PurchaseEntity purchaseEntity = new PurchaseEntity();
            purchaseEntity.setId(purchaseId);
            purchaseEntity.setUpdateTime(new Date());
            this.updateById(purchaseEntity);
        }
    }

    /**
     * 采购人员领取采购单
     * 不属于后台管理系统接口，属于采购人员在自己手机app中调用生效
     */
    @Override
    @Transactional
    public void received(List<Long> ids) {
        //1.确认当前采购单的状态是新建或者已分配，这两个状态才可以被采购人员领取
        List<PurchaseEntity> purchaseEntityList = baseMapper.selectBatchIds(ids);
        List<PurchaseEntity> purchaseEntities = purchaseEntityList.stream().filter(item -> {
            if (item.getStatus() == WareConstant.PurchaseStatusEnum.CREATED.getCode() ||
                    item.getStatus() == WareConstant.PurchaseStatusEnum.ASSIGNED.getCode()) {
                return true;
            }
            return false;
        }).collect(Collectors.toList());
        //2.改变采购单的状态为已领取
        for (PurchaseEntity purchaseEntity : purchaseEntities) {
            purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.RECEIVE.getCode());
            purchaseEntity.setUpdateTime(new Date());
        }
        this.updateBatchById(purchaseEntities);
        //3.改变采购需求的状态为正在采购
        purchaseEntities.forEach(item -> {
            //根据每个采购单id查出它对应的所有采购需求
            List<PurchaseDetailEntity> entityList = purchaseDetailService.listByPurchaseId(item.getId());
            //将每个采购需求的状态改为正在采购
            List<PurchaseDetailEntity> purchaseDetailEntityList = entityList.stream().map(entity -> {
                PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
                purchaseDetailEntity.setId(entity.getId());
                purchaseDetailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.BUYING.getCode());
                return purchaseDetailEntity;
            }).collect(Collectors.toList());
            purchaseDetailService.updateBatchById(purchaseDetailEntityList);
        });
    }

    /**
     * 完成采购
     */
    @Override
    @Transactional
    public void done(FinishPurchaseVo finishPurchaseVo) {
        //1.改变采购单中每个采购需求的状态，可能成功，也可能失败
        Long purchaseId = finishPurchaseVo.getId();
        boolean flag = true;
        List<PurchaseItemVo> items = finishPurchaseVo.getItems();
        List<PurchaseDetailEntity> detailEntityList = new ArrayList<>();
        for (PurchaseItemVo item : items) {
            PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
            purchaseDetailEntity.setId(item.getItemId());
            if (item.getStatus() == WareConstant.PurchaseDetailStatusEnum.HASERROR.getCode()) {
                flag = false;
                purchaseDetailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.HASERROR.getCode());
            } else {
                purchaseDetailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.FINISH.getCode());
                //根据id查询对应采购成功的采购需求，最后插入wms_ware_sku表
                PurchaseDetailEntity entity = purchaseDetailService.getById(item.getItemId());
                Long skuId = entity.getSkuId();
                Long wareId = entity.getWareId();
                Integer skuNum = entity.getSkuNum();
                wareSkuService.saveOrUpdateWareSku(skuId, wareId, skuNum);
            }
            detailEntityList.add(purchaseDetailEntity);
        }
        purchaseDetailService.updateBatchById(detailEntityList);
        //2.改变采购单的状态为已完成
        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(purchaseId);
        //上面的for循环如果有一个采购需求的状态失败了flag=false，则采购单的状态不算完成
        purchaseEntity.setStatus(flag ?
                WareConstant.PurchaseStatusEnum.FINISH.getCode() : WareConstant.PurchaseStatusEnum.HASERROR.getCode());
        purchaseEntity.setUpdateTime(new Date());
        this.updateById(purchaseEntity);
    }
}